$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPAPLYWO : "XPAPLYWO",
        T_XPAPLYDN : "XPAPLYDN",
        T_XPBMDLDF : "XPBMDLDF",
        T_XPBISCUS : "XPBISCUS",
        DISABLED_ATTR: {disabled:true},
        ENABLED_ATTR : {disabled:false}
    };

    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                  : $(window)             ,
        dnNOTxt            : $("#dnNOTxt")         ,
        shipDatepicker     : $("#shipDatepicker")  ,
        shipTimepicker     : $("#shipTimepicker")  ,
//        shipDateTxt        : $("#shipDateTxt")     ,
//        shipTimeTxt        : $("#shipTimeTxt")     ,
        shipAddressTxt     : $("#shipAddressTxt")  ,
        mdlIdSel           : $("#mdlIdSel")        ,
        woIDSel            : $("#woIDSel")         ,
        totalQtyTxt        : $("#totalQtyTxt")     ,
        rlPrdQtyTxt        : $("#rlPrdQtyTxt")     ,
        wipQtyTxt          : $("#wipQtyTxt")       ,
        whInQtyTxt         : $("#whInQtyTxt")      ,
        whOutQtyTxt        : $("#whOutQtyTxt")     ,//已出货数量
        scrpQtyTxt         : $("#scrpQtyTxt")      ,
        shipQtyTxt         : $("#shipQtyTxt")      ,//出货数量
        shipNoteTxt        : $("#shipNoteTxt")     ,
        cusIDSel           : $("#cusIDSel"),
        shipCusIDSel       : $("#shipCusIDSel"),
        addressSequeceSel  : $("#addressSequeceSel"),
        //autoDnBtn          : $("#autoDnBtn"),
        evtSeqId           : $("#evt_seq_id"),
        mainGrd   :{
            grdId     : $("#dnListGrd")   ,
            grdPgText : "#dnListPg"       ,
            fatherDiv : $("#dnListDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1_query : $("#f1_query_btn"),
        f3_exit  : $("#f3_exit_btn"),
        f4_del   : $("#f4_del_btn"),
        f5_upd   : $("#f5_upd_btn"),
        f8_regist: $("#f8_regist_btn"),
        f10_clear: $("#f10_clear_btn"),
        f9_cancel: $("#f9_cancel_update_btn"),
        export_btn : $("#export_btn"),
		f6_close_btn : $("#f6_close_btn"),
		f7_open_btn : $("#f7_open_btn")
    };

    var baseFnc = {
    		ComL2S : function (data1, length, data2) {
    			if (length <= 0) {
    				return null;
    			}
    			var str = data1.toString();
    			if (data1.length > length) {
    				return null;
    			}
    			var size = str.length;
    			var chazhi = length - size;
    			for (var i = 0; i < chazhi; i++) {
    				str = data2 + str;
    			}
    			return str;
    		},
    		replaceSpace:function(str){
    			if(!str){
    				return str;
    			}
    			return str.replace(/[ ]/g,"@");	
    		},
    		returnSpace:function(str){
    			if(!str){
    				return str;
    			}
    			return str.replace(/[@]/g," ");
    		}
	};
    
    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            $("input").val("");
            // controlsQuery.toolGrpCheckbox.removeAttr("checked");
        },
        setEnable : function(){
            controlsQuery.dnNOTxt.attr({"disabled":false});
            controlsQuery.woIDSel.attr({"disabled":false});
            controlsQuery.cusIDSel.attr({"disabled":false});
            controlsQuery.shipCusIDSel.attr({"disabled":false});
            controlsQuery.mdlIdSel.attr({"disabled":false});
        },
        /**
         * Set data for select
         * @param dataCnt
         * @param arr
         * @param selVal
         * @param queryObj
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            queryObj.append("<option ></option>");

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>");
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }
            
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        convertTimestamp2Date : function(timestamp) {
			var date = new Date(timestamp.substring(0, 10));
			date.setHours(timestamp.substring(11, 13));
			date.setMinutes(timestamp.substring(14, 16));
			date.setSeconds(timestamp.substring(17, 19));
			return date;
		},
        iniShipDateTxt: function(){
        	var datepickerData, datepickerTime;

        	controlsQuery.shipDatepicker.datetimepicker({
						language : 'zh-CN',
						autoclose: true,
						pickTime : false
					});
        	controlsQuery.shipDatepicker.datetimepicker().on('changeDate', function(ev){
        		controlsQuery.shipDatepicker.datetimepicker('hide');
			});


			
        	controlsQuery.shipTimepicker.datetimepicker({
						language : 'zh-CN',
						autoclose: true,
						pickDate : false
					});


			datepickerData = controlsQuery.shipDatepicker.data("datetimepicker");
			datepickerData.setLocalDate(datepickerData.getLocalDate());

			datepickerTime = controlsQuery.shipTimepicker.data("datetimepicker");
			datepickerTime.setLocalDate(new Date());
//          $( "#shipDateTxt" ).datepicker({
//                defaultDate    : "",
//                dateFormat     : 'yy-mm-dd',
//                changeMonth    : true,
//                changeYear     : true,
//                numberOfMonths : 1
//          });
        },
        iniMdlIdSelect: function(){
        	var inObj,outObj,tblCnt,i,oary;
        	SelectDom.initWithSpace(controlsQuery.mdlIdSel);
        	inObj = {
        		trx_id     : VAL.T_XPBMDLDF,
        		action_flg : "Q",
        		iary       : {}
        	};
        	outObj = comTrxSubSendPostJson(inObj);
        	if(outObj.rtn_code === VAL.NORMAL){
//        		toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "mdl_id", controlsQuery.mdlIdSel);
        		tblCnt = outObj.tbl_cnt;
        		for(i=0;i<tblCnt;i++){
        			oary = tblCnt > 1 ?  outObj.oary[i]: outObj.oary;
        			SelectDom.addSelect(controlsQuery.mdlIdSel, baseFnc.replaceSpace(oary.mdl_id), oary.mdl_id);
        		}
        	}
        },
        mdlIDChangeFnc:function(){
        	var inObj,outObj,mdlId,cusId;
//        	mdlId = controlsQuery.mdlIdSel.find("option:selected").text();
        	mdlId = baseFnc.returnSpace(controlsQuery.mdlIdSel.val());
        	cusId = controlsQuery.cusIDSel.val();
        	inObj = {
        		trx_id     : VAL.T_XPAPLYWO ,
        		action_flg : "Q",
        		iary       : {
//        			mdl_id : mdlId,
//        			wo_stat: "WAIT"
                    wo_stats : "'WAIT','CLOS'"
        		}
        	};
        	if(!mdlId || mdlId === " "){
        		controlsQuery.woIDSel.val("");
        		toolFunc.setSelectDate("1", "", "", controlsQuery.woIDSel);
//        		return false;
        	}else{
        		inObj.iary.mdl_id = mdlId;        		
        	}
        	
        	if(cusId){
        		inObj.iary.cus_id = cusId;    
        	}
        	outObj = comTrxSubSendPostJson(inObj);
        	if(outObj.rtn_code === VAL.NORMAL){
        		toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", controlsQuery.woIDSel);
        	}
        },
        iniWoIdSelect : function(){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q',
                iary        : {
                    wo_stat : "WAIT"
                }
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", controlsQuery.woIDSel);
            }
        },
        woIDChangeFnc:function(){
            var wo_id ,
                inObj ,
                outObj,
                oary;
                wo_id =controlsQuery.woIDSel.val();
            if( wo_id==""|| wo_id == null){
                controlsQuery.totalQtyTxt.text("");
                controlsQuery.rlPrdQtyTxt.text("");
                controlsQuery.wipQtyTxt.text("");
                controlsQuery.whInQtyTxt.text("");
                controlsQuery.whOutQtyTxt.text("");
                controlsQuery.scrpQtyTxt.text("");
                return false;
            } 
            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q',
                iary        :{}  
            };
            if(wo_id){
            	inObj.iary.wo_id = wo_id;
            }
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code==VAL.NORMAL){
                oary = outObj.oary;
                controlsQuery.totalQtyTxt.text(oary.pln_prd_qty);
                controlsQuery.rlPrdQtyTxt.text(parseInt(oary.rl_prd_qty,10));
                controlsQuery.wipQtyTxt.text(parseInt(oary.rl_prd_qty,10) - parseInt(oary.wh_in_prd_qty,10) - parseInt(oary.wh_out_prd_qty,10) - parseInt(oary.wip_wh_in_prd_qty,10) );
                controlsQuery.whInQtyTxt.text(parseInt(oary.wh_in_prd_qty,10) + parseInt(oary.wip_wh_in_prd_qty,10));
                controlsQuery.whOutQtyTxt.text(oary.wh_out_prd_qty);
                controlsQuery.scrpQtyTxt.text(oary.scrp_prd_qty);
                SelectDom.setSelect(controlsQuery.cusIDSel,oary.cus_id_fk);
//                toolFunc.cusSelChangeFnc();
                SelectDom.setSelect(controlsQuery.mdlIdSel,baseFnc.replaceSpace(oary.mdl_id),oary.mdl_id);
                SelectDom.setSelect(controlsQuery.shipCusIDSel,oary.cus_id_fk);
            }
            controlsQuery.woIDSel.val(wo_id);
            controlsQuery.woIDSel.select2({
		    	theme : "bootstrap"
		    });


        },
        dnNOTxtFocusLost:function(){
            var inObj,
                outObj,
                tblCnt,
                oary,
                i;
            inObj = {
                trx_id     : "XPAPLYDN" ,
                action_flg : "Q"        ,
                iary       :{
                    dn_no : controlsQuery.dnNOTxt.val()
                }
            };
            outObj = comTrxSubSendPostJson(inObj,"N");
            tblCnt =outObj.tbl_cnt;
            if(outObj.rtn_code==VAL.NORMAL && tblCnt>0){
            	oary = tblCnt > 1 ? outObj.oary[0] : outObj.oary;
            	if(oary.shipping_timestamp == undefined){
            		return;
            	}
            	controlsQuery.shipDatepicker.data("datetimepicker").setLocalDate(this.convertTimestamp2Date(oary.shipping_timestamp));
    			controlsQuery.shipTimepicker.data("datetimepicker").setLocalDate(this.convertTimestamp2Date(oary.shipping_timestamp));
            }

        },
        iniCusSel:function(){
        	 var inObj,
             outObj;
        	 inObj = {
        		trx_id     :"XPLSTDAT",
        		action_flg :"Q",
        		iary       :{
        			data_cate :"CUSD"
        		}
        	 };
        	 outObj = comTrxSubSendPostJson(inObj);
        	 if(outObj.rtn_code==VAL.NORMAL && outObj.oary !=undefined){
        		 toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "data_item", controlsQuery.cusIDSel);
        		 toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "data_item", controlsQuery.shipCusIDSel);
             }
//        	  setSelectObjValueTxtByData("#cusIDSel","CUSD","data_item","data_item");
        	  
        },
        cusSelChangeFnc:function(){
        	var inObj,iary,outObj,tblCnt,oary,i,cus_id,mdl_id,seq=1;
             	mdlId = baseFnc.returnSpace(controlsQuery.mdlIdSel.val());        	
        		controlsQuery.addressSequeceSel.empty();
        		controlsQuery.shipAddressTxt.val("");
        		SelectDom.setSelect(controlsQuery.shipCusIDSel,controlsQuery.cusIDSel.val(),controlsQuery.cusIDSel.find("option:selected").text());
        		
        		cus_id = controlsQuery.cusIDSel.val();
        		
        		iary = {
    				cus_id_fk : controlsQuery.cusIDSel.val()
    			};
        		inObj = {
    				trx_id : VAL.T_XPBISCUS,
    				action_flg:'Q',
    				iary: iary
    			};
        		outObj = comTrxSubSendPostJson(inObj);
        	 
        	 SelectDom.initWithSpace(controlsQuery.addressSequeceSel);	
           	 if(outObj.rtn_code==VAL.NORMAL && outObj.oary !=undefined){
           		for(i=0;i<outObj.tbl_cnt;i++){
           			oary = outObj.tbl_cnt>1 ?outObj.oary[i]:outObj.oary;
           			if(oary.loc_type=="R"){
           				SelectDom.addSelect(controlsQuery.addressSequeceSel, oary.loc_info, ("地址"+seq));
           				seq++;
           			}
           		}
           		toolFunc.addressSequeceSelChangeFnc();
             }
           	 
         	inObj = {
            		trx_id     : VAL.T_XPAPLYWO ,
            		action_flg : "Q",
            		iary       : {
                        wo_stats : "'WAIT','CLOS'"
            		}
            	};
            if(cus_id){
            	inObj.iary.cus_id = cus_id;
            }
            if(mdl_id){
            	inObj.iary.mdl_id = mdl_id;
            }
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code === VAL.NORMAL){
            	toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", controlsQuery.woIDSel);
            }
           	 //根据客户 过滤 产品
           	 iary  = {
           		cus_id : cus_id	 
           	 };
           	 inObj = {
           		trx_id     : VAL.T_XPBMDLDF,
           		action_flg : "C",
           		iary       : iary
           	 };
           	 outObj = comTrxSubSendPostJson(inObj);
           	 if(outObj.rtn_code === VAL.NORMAL){
         		_setSelectDate(outObj.tbl_cnt,outObj.oary,"mdl_id","mdl_id",controlsQuery.mdlIdSel,true);

           	 }
        },
        addressSequeceSelChangeFnc:function(){
        	controlsQuery.shipAddressTxt.val(controlsQuery.addressSequeceSel.val());
        },
        
        autoDnFnc:function (){
        	var inTrx, outTrx, serialNO;
    		inTrx = {
    			trx_id : "XPCRTNO",
    			action_flg : "N",
    			type : "N"
    		};
    		outTrx = comTrxSubSendPostJson(inTrx);
    		if (outTrx.rtn_code == "0000000") {
    			controlsQuery.dnNOTxt.val(outTrx.serial_no);
    			controlsQuery.dnNOTxt.attr({
    				"disabled" : true
    			});
    		}
        }
    }; 

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_query : function(){
            var inObj,
                outObj,
                dn_no,
                wo_id_fk;
            var iary ={};
            wo_id_fk = controlsQuery.woIDSel.find("option:selected").text();

            if( wo_id_fk != null  && wo_id_fk != "" ) {
                iary.wo_id_fk = wo_id_fk;
            }
            dn_no = controlsQuery.dnNOTxt.val().trim();
            if(dn_no !=null && dn_no !=""){
                iary.dn_no = dn_no;
            }
            inObj = {
                trx_id      : "XPAPLYDN",
                action_flg  : "Q"           ,
                iary        : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, "#dnListGrd");
            }
        },
        f4_del:function(){
            var selectRowID,
                rowData,
                dn_no,
                wo_id_fk,
                inObj,
                outObj;
            selectRowID = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selrow");
            if(selectRowID==""||selectRowID==null){
                showErrorDialog("","请选择需要删除的记录");
                return false;
            }
            btnQuery.f4_del.showCallBackWarnningDialog({
                errMsg  : "是否删除次笔记录,请确认!!!!",
                callbackFn : function(data) {
                    if(data.result==true){
                        rowData = controlsQuery.mainGrd.grdId.jqGrid("getRowData",selectRowID);
                        dn_no    = rowData.dn_no;
                        wo_id_fk = rowData.wo_id_fk;
                        evt_seq_id = rowData.evt_seq_id;
                        inObj ={
                            trx_id      : "XPAPLYDN",
                            action_flg  : "D",
                            tbl_cnt     : 1,
                            iary        :{
                                dn_no    : dn_no ,
                                wo_id_fk : wo_id_fk,
                                evt_seq_id : evt_seq_id
                            }
                        }
                        outObj = comTrxSubSendPostJson(inObj);
                        if(outObj.rtn_code==VAL.NORMAL){
                           showSuccessDialog("出货单删除成功"); 
                           controlsQuery.mainGrd.grdId.jqGrid("delRowData",selectRowID);
                        }
                    }
                }
            })
            

        },
        f5_upd:function(){
            var dn_no,
                dn_stat,
                ship_address,
                ship_car_id,
                ship_date,
                ship_time,
                shipping_timestamp,
                ship_note,
                ship_qty,
                cus_id,
                ship_usr,
                wo_id_fk,
                inObj,
                outObj,
                iary,
                evt_seq_id;

            if(controlsQuery.dnNOTxt.attr("disabled")!=="disabled"){
            	showErrorDialog("","当前不在编辑状态,请在列表中双击修改的行");
            	return false;
            }	
            dn_no = controlsQuery.dnNOTxt.val();
            if(!dn_no){
                showErrorDialog("","请输入交货订单号");
                return false;
            }
            wo_id_fk = controlsQuery.woIDSel.find("option:selected").text();
            if(!wo_id_fk){
                showErrorDialog("","请选择需要绑定的内部订单");
                return false;
            }
            ship_date = controlsQuery.shipDatepicker.data("datetimepicker").getLocalDate().format('yyyy-MM-dd');
            ship_time = controlsQuery.shipTimepicker.data("datetimepicker").getLocalDate().format('hh:mm:ss');
            
            if(!ship_date){
            	showErrorDialog("","请选择出货日期");
            	return false;
            }
            if(!ship_time){
            	showErrorDialog("","请选择出货时间");
            	return false;
            }
            shipping_timestamp = ship_date + " " + ship_time ;
            
            cus_id = controlsQuery.cusIDSel.val();
            if(!cus_id){
            	showErrorDialog("","请选择客户代码");
            	return false;
            }
            ship_usr = controlsQuery.shipCusIDSel.val();
            if(!ship_usr){
            	showErrorDialog("","请选择出货客户代码");
            	return false;
            }
            evt_seq_id = controlsQuery.evtSeqId.val();
            if(!evt_seq_id){
            	showErrorDialog("","该条数据有问题，请查看evt_seq_id!");
            	return false;
            }
            
//            ship_date = controlsQuery.shipDateTxt.val();
//
//            if( !ship_date ){
//                showErrorDialog("01","交货日期不能为空");
//                return false;
//            }
//            ship_time = controlsQuery.shipTimeTxt.val();
//            if( ship_time ==null || ship_time ==""){
//                showErrorDialog("01","交货时间不能为空");
//                return false;
//            }
            iary = {
                dn_no        : dn_no,
                cus_id       : cus_id,
                ship_usr     : ship_usr,
                ship_date    : ship_date,
                ship_time    : ship_time,
                shipping_timestamp :shipping_timestamp,  
                ship_address : controlsQuery.shipAddressTxt.val(),
                ship_qty     : comParseInt( controlsQuery.shipQtyTxt.val() ),
                wo_id_fk     : wo_id_fk,
                ship_note    : controlsQuery.shipNoteTxt.val(),
                evt_usr      : VAL.EVT_USER,
                evt_seq_id   : evt_seq_id

            }
            inObj={
                trx_id     : "XPAPLYDN",
                action_flg : "U"       ,
                tbl_cnt    : 1         ,
                iary       : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code==VAL.NORMAL){
                showSuccessDialog("出货单修改成功"); 
                btnQuery.f9_cancel.hide();
                btnQuery.f1_query.show();
                btnQuery.f4_del.show();
                btnQuery.f8_regist.show();
                btnQuery.f10_clear.show();
                controlsQuery.dnNOTxt.attr(VAL.ENABLED_ATTR);
                controlsQuery.woIDSel.attr(VAL.ENABLED_ATTR);
                controlsQuery.cusIDSel.attr(VAL.ENABLED_ATTR);
                controlsQuery.mdlIdSel.attr(VAL.ENABLED_ATTR);
                controlsQuery.shipCusIDSel.attr(VAL.ENABLED_ATTR);
                /*selectRowID = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selrow");
                if(selectRowID){
                    controlsQuery.mainGrd.grdId.jqGrid("setRowData",selectRowID,outObj.oary);
                }*/
                btnFunc.f1_query();
            }

        },
        f8_regist_continue: function(iary){
                var inObj,outObj,newGridRowID;
                inObj={
                    trx_id     : "XPAPLYDN",
                    action_flg : "A"       ,
                    tbl_cnt    : 1         ,
                    iary       : iary
                };
                outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code==VAL.NORMAL){
                    showSuccessDialog("新增成功"); 
                    controlsQuery.dnNOTxt.attr({
        				"disabled" : false
        			});
                    controlsQuery.dnNOTxt.val("");
                    inObj={
                       trx_id      : "XPAPLYDN",
                        action_flg : "Q"       ,
                        tbl_cnt    : 1         ,
                        iary       : iary/* {
                            dn_no    : dn_no   ,
                            wo_id_fk : wo_id_fk
                        } */
                    };
                    outObj = comTrxSubSendPostJson(inObj);
                    newGridRowID = getGridNewRowID("#dnListGrd");
                    controlsQuery.mainGrd.grdId.jqGrid("addRowData",newGridRowID,outObj.oary);
                }
        },
        f8_regist : function(){
            var dn_no,
                dn_stat,
                ship_address,
                ship_car_id,
                ship_date,
                ship_time,
                shipping_timestamp,
                ship_note,
                ship_qty,
                wo_un_ship_qty,
                ship_usr,
                wo_id_fk,
                cus_id,
                ship_cus_id,
                inObj,
                outObj,
                inObj2,
                outObj2,
                newGridRowID;

            dn_no = controlsQuery.dnNOTxt.val();
            if(!dn_no){
                showErrorDialog("","请输入交货订单号");
                return false;
            }
            wo_id_fk = controlsQuery.woIDSel.find("option:selected").text();
            if(!wo_id_fk){
                showErrorDialog("","请选择需要绑定的内部订单");
                return false;
            }
            if("" === $("#shipDatepicker input").val() || "" === $("#shipTimepicker input").val() ){
            	showErrorDialog("","请选择出货时间");
            	return false;
            }
            ship_date = controlsQuery.shipDatepicker.data("datetimepicker").getLocalDate().format('yyyy-MM-dd');
            ship_time = controlsQuery.shipTimepicker.data("datetimepicker").getLocalDate().format('hh:mm:ss');
            
            if(!ship_date){
            	showErrorDialog("","请选择出货日期");
            	return false;
            }
            if(!ship_time){
            	showErrorDialog("","请选择出货时间");
            	return false;
            }
            shipping_timestamp = ship_date + " " + ship_time ;
            
//            ship_date = controlsQuery.shipDateTxt.val();
//
//            if( !ship_date ){
//                showErrorDialog("01","交货日期不能为空");
//                return false;
//            }
            
            //交货数量<=内部订单数量-已出货数量
            ship_qty = comParseInt( controlsQuery.shipQtyTxt.val() );
            if( ship_qty == 0 ){           	
            	showErrorDialog("","交货数量必须大于0");
            	return false;
            }
            wo_un_ship_qty = comParseInt(controlsQuery.totalQtyTxt.text())-comParseInt(controlsQuery.whOutQtyTxt.text()); 
//            if( ship_qty > wo_un_ship_qty ){
//            	showErrorDialog("","交货数量不能 大于 (内部订单数量["+ controlsQuery.totalQtyTxt.text() +"]-已出货数量["+ controlsQuery.whOutQtyTxt.text() +"])")
//            	return false;
//            }
            
//            if(comParseInt(ship_qty)>comParseInt(controlsQuery.rlPrdQtyTxt.text())){
//            	showErrorDialog("","交货数量不能大于内部订单投入数量");
//            	return false;
//            }
            cus_id = controlsQuery.cusIDSel.val();
            ship_cus_id = controlsQuery.shipCusIDSel.val();
            if(!cus_id){
            	showErrorDialog("","请选择客户");
            	return false;
            }
            if(!ship_cus_id){
            	showErrorDialog("","请选择出货客户");
            	return false;
            }

   	       iary = {
               dn_no        : dn_no,
               ship_date    : ship_date,
               ship_time    : ship_time,
               shipping_timestamp:shipping_timestamp,
               ship_address : controlsQuery.shipAddressTxt.val(),
               ship_qty     : ship_qty,
               cus_id       : cus_id,
               ship_cus_id  : ship_cus_id,
               wo_id_fk     : wo_id_fk,
               ship_note    : controlsQuery.shipNoteTxt.val(),
               evt_usr      : VAL.EVT_USER
           };
   
            if(cus_id !== ship_cus_id){
                btnQuery.f8_regist.showCallBackWarnningDialog({
                    errMsg  : "所选交货客户"+ship_cus_id+"不是来料客户"+cus_id+",是否确定?!!",
                    callbackFn : function(data) {
                        if(data.result==true){
                        	btnFunc.f8_regist_continue(iary);
                        }
                    }
                });
            }else{
            	btnFunc.f8_regist_continue(iary);
            }
        },
        f9_cancel:function(){
            btnQuery.f9_cancel.hide();
            btnQuery.f1_query.show();
            btnQuery.f4_del.show();
            btnQuery.f8_regist.show();
            btnQuery.f10_clear.show();
            controlsQuery.dnNOTxt.attr(VAL.ENABLED_ATTR);
            controlsQuery.woIDSel.attr(VAL.ENABLED_ATTR);
            controlsQuery.cusIDSel.attr(VAL.ENABLED_ATTR);
            controlsQuery.mdlIdSel.attr(VAL.ENABLED_ATTR);
            controlsQuery.shipCusIDSel.attr(VAL.ENABLED_ATTR);
            controlsQuery.dnNOTxt.attr({
				"disabled" : false
			});
        },f10_clear:function(){
        	$("span").text("");
        	$("input[type='text']").val("");
        	SelectDom.setSelect($("select"), "", " ");
	     	toolFunc.iniWoIdSelect();
        	toolFunc.iniMdlIdSelect();  
        	controlsQuery.dnNOTxt.attr({
				"disabled" : false
			});
        },
        exportExcel :function(){
        	generateExcel(controlsQuery.mainGrd.grdId);
        },
		f6_close : function() {
			var rowIds, rowCnt, rowData, i, inObj, iary, outObj, useId,closeRowID;

			usrId = $("#userId").text();
			closeRowID = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selrow");
			if (!closeRowID) {
				showErrorDialog("001", "选择需要关闭的交货订单");
				return false;
			}
			iary = [];
			rowData = controlsQuery.mainGrd.grdId.jqGrid("getRowData", closeRowID);
			iary.push({
				dn_no : rowData.dn_no,
				wo_id_fk : rowData.wo_id_fk,
				evt_usr : usrId
			})

			btnQuery.f6_close_btn.showCallBackWarnningDialog({
						errMsg : "是否关闭订单[" + rowData.dn_no + "]?",
						callbackFn : function(data) {
							if (data.result == true) {
								inTrx = {
									trx_id      : "XPAPLYDN",
			                        action_flg  : "X",
									iary : iary
								};
								outObj = comTrxSubSendPostJson(inTrx);
								if (outObj.rtn_code == VAL.NORMAL) {
									showSuccessDialog("交货订单关闭成功");
									btnFunc.f1_query();
								}

							}
						}
					})
		},
		f7_open : function() {
			var rowIds, rowCnt, rowData, i, inObj, iary, outObj, useId,openRowID;

			usrId = $("#userId").text();
			openRowID = controlsQuery.mainGrd.grdId.jqGrid("getGridParam","selrow");
			if (!openRowID) {
				showErrorDialog("001", "选择需要打开的交货订单");
				return false;
			}
			iary = [];
			rowData = controlsQuery.mainGrd.grdId.jqGrid("getRowData", openRowID);
			iary.push({
				dn_no : rowData.dn_no,
				wo_id_fk : rowData.wo_id_fk,
				evt_usr : usrId
			})

			inTrx = {
				trx_id      : "XPAPLYDN",
                action_flg  : "Y",
				iary : iary
			};
			outObj = comTrxSubSendPostJson(inTrx);
			if (outObj.rtn_code == VAL.NORMAL) {
				showSuccessDialog("交货订单打开成功！");
				btnFunc.f1_query();
			}
		}
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1_query.click(function(){
            btnFunc.f1_query();
        });
        btnQuery.f4_del.click(function(){
            btnFunc.f4_del();
        });
        btnQuery.f5_upd.click(function(){
            btnFunc.f5_upd();
        });
        btnQuery.f8_regist.click(function(){
            btnFunc.f8_regist();
        });
        btnQuery.f9_cancel.click(function(){
           btnFunc.f9_cancel();
        })
        btnQuery.f10_clear.click(btnFunc.f10_clear);
        btnQuery.export_btn.click(btnFunc.exportExcel);
        btnQuery.f6_close_btn.click(btnFunc.f6_close);
        btnQuery.f7_open_btn.click(btnFunc.f7_open);
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'evt_seq_id'       , index: 'evt_seq_id'     , label: CUS_ID_TAG,           width: CUS_ID_CLM,hidden:true},
	        {name: 'cus_id'           , index: 'cus_id'         , label: CUS_ID_TAG,           width: CUS_ID_CLM},
            {name: 'ship_cus_id'      , index: 'ship_cus_id'    , label: "交客",                width: CUS_ID_CLM},	        
			{name: 'crt_timestamp'    , index: 'crt_timestamp'  , label: "创建时间",             width: EVT_TIMESTAMP_CLM},
			{name: 'crt_usr'          , index: 'crt_usr'        , label: "制定人",              width: CUS_ID_CLM},
            {name: 'dn_no'            , index: 'dn_no'          , label: "交货订单号",            width: DN_NO_CLM},
            {name: 'dn_stat'          , index: 'dn_stat'        , label: "状态",               width: PRD_STAT_CLM},
            {name: 'plan_shipping_timestamp', index: 'plan_shipping_timestamp' , label: "计划交货时间",        width: EVT_TIMESTAMP_CLM},
			{name: 'shipping_timestamp', index: 'shipping_timestamp' , label: "交货时间",        width: EVT_TIMESTAMP_CLM},
            {name: 'so_id_fk'         , index: 'so_id_fk'       , label: CUS_ORDER_ID_TAG,    width: WO_ID_CLM},
            {name: 'real_so_id'       , index: 'real_so_id'     , label: "实际商务订单",           width: WO_ID_CLM},
            {name: 'wo_id_fk'         , index: 'wo_id_fk'       , label: WO_ID_TAG,            width: WO_ID_CLM},
            {name: 'pln_prd_qty'      , index: 'pln_prd_qty'    , label: SO_COUNT_TAG,         width: QTY_CLM},
            {name: 'rl_prd_qty'       , index: 'rl_prd_qty'     , label: "投入数",               width: QTY_CLM},
            {name: 'wo_space_dn_qty'  , index: 'wo_space_dn_qty', label: "未排数",               width: QTY_CLM},
            {name: 'wh_out_prd_qty'   , index: 'wh_out_prd_qty' , label: "总已交",             width: QTY_CLM},
            {name: 'ship_qty'         , index: 'ship_qty'       , label: "计交数",               width: QTY_CLM},
            {name: 'dn_wh_out_prd_qty', index: 'dn_wh_out_prd_qty' , label: WH_OUT_PRD_QTY_TAG,width: QTY_CLM},
            {name: 'wh_in_prd_qty'    , index: 'wh_in_prd_qty'  , label: WH_IN_PRD_QTY_TAG,    width: QTY_CLM},
            {name: 'scrp_prd_qty'     , index: 'scrp_prd_qty'   , label: SCRP_PRD_QTY_TAG,     width: QTY_CLM},
            {name: 'from_thickness'   , index: 'from_thickness' , label: FROM_THICKNESS_TAG,   width: QTY_CLM},
            {name: 'to_thickness'     , index: 'to_thickness'   , label: TO_THICKNESS_TAG,     width: QTY_CLM},
            {name: 'mtrl_prod_id_fk'  , index: 'mtrl_prod_id_fk', label: FROM_MTRL_ID_TAG,     width: MTRL_PROD_ID_CLM},
            {name: 'mdl_id_fk'        , index: 'mdl_id_fk'      , label: TO_MTRL_TYPE_TAG,     width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk'     , index: 'fm_mdl_id_fk'   , label: FM_MDL_ID_TAG,        width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk'    , index: 'cut_mdl_id_fk'  , label: CUT_MDL_ID_TAG,       width: MDL_ID_CLM},
            {name: 'ship_note'        , index: 'ship_note'      , label: REMARK_TAG,           width: SHIP_NOTE_CLM},
            {name: 'ship_usr'         , index: 'ship_usr'       , label: "交货客户",              width: CUS_ID_CLM,hidden:true},
            {name: 'ship_address'     , index: 'ship_address'   , label: "交货地址",              width: WO_NOTE_CLM,hidden:true}
            
        ];

        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:680,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            // multiselect : true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM,
            ondblClickRow:function(id){
                var rowData,
                    inObj,
                    outObj;
                btnQuery.f9_cancel.show();
                btnQuery.f1_query.hide();
                btnQuery.f4_del.hide();
                btnQuery.f8_regist.hide();
                btnQuery.f10_clear.hide();
                controlsQuery.dnNOTxt.attr({"disabled":true});
                controlsQuery.woIDSel.attr({"disabled":true});
                controlsQuery.cusIDSel.attr(VAL.DISABLED_ATTR);
                controlsQuery.mdlIdSel.attr(VAL.DISABLED_ATTR);
                controlsQuery.shipCusIDSel.attr(VAL.DISABLED_ATTR);

                rowData= $(this).jqGrid("getRowData",id);
                controlsQuery.dnNOTxt.val(rowData.dn_no);
                if("" === rowData.shipping_timestamp){
                	console.warn("shipping is NULL,please select");
                }else {
                	shippingTimestamp = TimestampUtil.convertTimestamp2Date(rowData.shipping_timestamp);
                	
                	controlsQuery.shipDatepicker.data("datetimepicker")
                	.setLocalDate(shippingTimestamp);
                	controlsQuery.shipTimepicker.data("datetimepicker")
                	.setLocalDate(shippingTimestamp);
                }
                controlsQuery.evtSeqId.val(rowData.evt_seq_id);
               SelectDom.setSelect(controlsQuery.woIDSel,rowData.wo_id_fk);
                SelectDom.setSelect(controlsQuery.cusIDSel,rowData.cus_id);
                SelectDom.setSelect(controlsQuery.shipCusIDSel,rowData.ship_cus_id);
                SelectDom.setSelect(controlsQuery.mdlIdSel,baseFnc.replaceSpace(rowData.mdl_id_fk),rowData.mdl_id_fk);
                controlsQuery.shipQtyTxt.val(rowData.ship_qty);
                controlsQuery.shipNoteTxt.val(rowData.ship_note);
                controlsQuery.evtSeqId.val(rowData.evt_seq_id);
                controlsQuery.shipAddressTxt.val(rowData.ship_address);
                toolFunc.woIDChangeFnc();              

            }
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        controlsQuery.woIDSel.change(function(){
            toolFunc.woIDChangeFnc();
        });
        controlsQuery.dnNOTxt.blur(function(){
            toolFunc.dnNOTxtFocusLost();    
        });
        controlsQuery.cusIDSel.change(function(){
        	toolFunc.cusSelChangeFnc();
        });
        controlsQuery.addressSequeceSel.change(function(){
        	toolFunc.addressSequeceSelChangeFnc();
        });
        controlsQuery.mdlIdSel.change(function(){
        	toolFunc.mdlIDChangeFnc();
        });
/*        controlsQuery.autoDnBtn.click(function (){
        	if(controlsQuery.dnNOTxt[0].disabled == false){
        		toolFunc.autoDnFnc();
        	}
        });*/
        
        

    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();
        //Wo info
        toolFunc.iniMdlIdSelect();
        toolFunc.iniWoIdSelect();
        toolFunc.iniShipDateTxt();
        toolFunc.setEnable();
        toolFunc.iniCusSel();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
    	btnQuery.f9_cancel.hide();
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
    function resizeFnc(){                                                                      
	  	var offsetBottom, divWidth;                                                              
	
	  	divWidth = controlsQuery.mainGrd.fatherDiv.width();                                   
		offsetBottom = controlsQuery.W.height() - controlsQuery.mainGrd.fatherDiv.offset().top;
		controlsQuery.mainGrd.fatherDiv.height(offsetBottom * 0.95);                          
		controlsQuery.mainGrd.grdId.setGridWidth(divWidth * 0.99);                   
		controlsQuery.mainGrd.grdId.setGridHeight(offsetBottom * 0.95 - 51);   
		$("#legendDiv").width(divWidth*0.99);
    };                                                                                         
    resizeFnc();                                                                               
    controlsQuery.W.resize(function() {                                                         
    	resizeFnc();                                                                             
    });
});

